<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportDate">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="userList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" sortable="" type="index" width="180">
            <template #default="{row}">
              <img v-imgerr="require('@/assets/common/pkq.png')" :src="row.staffPhoto" alt="" class="avatar" @click="showQRcodeFn(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployFn" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="{row}">
              <el-switch
                v-model="row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="2"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" prop="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRoleFn(row.id)">角色</el-button>
              <el-button type="text" size="small" @click.="deleEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :page-size="pageSetting.size" :total="total" @current-change="currentChangeFn" />
        </el-row>
      </el-card>
      <addEmployee :show-dialog.sync="showDialog" />
      <el-dialog title="头像转二维码" :visible="showQRcode" @close="showQRcode=false">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <assignRole ref="assignRole" :show-dialog.sync="showAssignRole" />
    </div>
  </div>
</template>

<script>
import { getUserList, delEmployeeApi } from '@/api/employees'
import employess from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters/index'
import addEmployee from './component/add-employee.vue'
import qrcode from 'qrcode'
import assignRole from './component/assign-role.vue'
export default {
  components: {
    addEmployee, assignRole
  },
  data() {
    return {
      total: 0,
      userList: [],
      pageSetting: { page: 1, size: 5 },
      showDialog: false,
      showQRcode: false,
      showAssignRole: false
    }
  }, created() {
    this.getUserListFn()
  },
  methods: {
    // 显示角色管理
    async assignRoleFn(id) {
      await this.$refs.assignRole.getRoleDetailsFn(id)
      this.showAssignRole = true
    },
    // 显示二维码
    showQRcodeFn(url) {
      this.showQRcode = true
      // console.log(url)
      this.$nextTick(() => {
        qrcode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    // 获取员工信息列表函数
    async getUserListFn() {
      const { total, rows } = await getUserList(this.pageSetting)
      this.total = total
      this.userList = rows
    },
    // 切换分页
    currentChangeFn(val) {
      this.pageSetting.page = val
      this.getUserListFn()
    },
    // 格式化聘用方式
    formatEmployFn(row, col, cell, index) {
      const obj = employess.hireType.find(item => item.id === cell)
      return obj ? obj.value : '未知'
    },
    // 导出员工数据
    async exportDate() {
      const header = ['姓名', '手机号', '工号', '聘用形式', '入职日期']
      const { rows } = await getUserList({
        page: 1,
        size: this.total
      })
      // //console.log(rows)
      const data = rows.map(item => {
        return this.transfrom({ ...item })
      })
      // console.log(data)
      export_json_to_excel({
        header,
        data
      })
    },
    // 数据对象转二维数组
    transfrom(val) {
      const newArr = []
      const headers = ['姓名', '手机号', '工号', '聘用形式', '入职日期']
      const dictionarise = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      headers.forEach(item => {
        const enkey = dictionarise[item]
        const value = val[enkey]
        if (enkey === 'timeOfEntry') {
          newArr.push(formatDate(value))
        } else if (enkey === 'formOfEmployment') {
          const obj = employess.hireType.find(item => item.id === value)
          const res = obj ? obj.value : '未知'
          newArr.push(res)
        } else {
          newArr.push(value)
        }
      })

      return newArr
    },
    // 删除员工
    async  deleEmployee(id) {
      await this.$confirm('确定要删除该员工吗？')
      await delEmployeeApi(id)
      this.message.success('删除成功')
      this.getUserListFn()
    }

  }
}
</script>

<style lang="scss" scoped>
.avatar{
  height: 150px;
  object-fit:cover;
}
</style>
